<template>
  <div class="department-form">
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px">
      <el-form-item label="上级科室" v-if="form.level === 2">
        <el-tree-select
          v-model="form.parentId"
          :data="parentDepartments"
          node-key="id"
          :props="{
            label: 'name',
            value: 'id',
            children: 'children',
            disabled: (data) => data.level === 2
          }"
          placeholder="请选择上级科室"
          :render-after-expand="false"
          check-strictly
          disabled
        />
      </el-form-item>
      <el-form-item label="科室名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入科室名称" />
      </el-form-item>
      <el-form-item label="科室编码" prop="code">
        <el-input v-model="form.code" placeholder="请输入科室编码" :disabled="!!form.id" />
      </el-form-item>
      <el-form-item label="描述">
        <el-input v-model="form.description" type="textarea" placeholder="请输入科室描述" />
      </el-form-item>
      <el-form-item label="位置">
        <el-input v-model="form.location" placeholder="请输入科室位置" />
      </el-form-item>
      <el-form-item label="联系电话">
        <el-input v-model="form.phone" placeholder="请输入联系电话" />
      </el-form-item>
      <el-form-item label="排序号">
        <el-input-number v-model="form.sortOrder" :min="0" :max="999" />
      </el-form-item>
      <el-form-item label="状态">
        <el-switch
          v-model="form.status"
          :active-value="1"
          :inactive-value="0"
          active-text="启用"
          inactive-text="停用"
        />
      </el-form-item>
    </el-form>
    <div class="dialog-footer">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="submitting">确定</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { addDepartment, updateDepartment } from '@/api/admin'

const props = defineProps({
  id: {
    type: Number,
    default: null
  },
  parentId: {
    type: Number,
    default: null
  },
  level: {
    type: Number,
    default: 1
  },
  parentDepartments: {
    type: Array,
    default: () => []
  },
  initialData: {
    type: Object,
    default: () => ({})
  }
})

const emit = defineEmits(['close'])

const formRef = ref(null)
const submitting = ref(false)

// 表单数据
const form = ref({
  id: props.id,
  parentId: props.parentId,
  level: props.level,
  name: '',
  code: props.level === 2 ? `${props.initialData.parentCode}_` : '',
  description: '',
  location: '',
  phone: '',
  sortOrder: 0,
  status: 1,
  ...props.initialData
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入科室名称', trigger: 'blur' },
    { min: 2, max: 50, message: '科室名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入科室编码', trigger: 'blur' },
    { min: 2, max: 20, message: '科室编码长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
}

// 取消
const handleCancel = () => {
  emit('close')
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      try {
        const submitFunc = form.value.id ? updateDepartment : addDepartment
        const response = await submitFunc(form.value)
        if (response.code === 200) {
          ElMessage.success(form.value.id ? '更新成功' : '添加成功')
          emit('close', true) // 传递成功标志
        } else {
          ElMessage.error(response.message || (form.value.id ? '更新失败' : '添加失败'))
        }
      } catch (error) {
        console.error('保存科室失败:', error)
        ElMessage.error(form.value.id ? '更新失败' : '添加失败')
      } finally {
        submitting.value = false
      }
    }
  })
}
</script>

<style scoped>
.department-form {
  padding: 20px;
}

.dialog-footer {
  text-align: right;
  margin-top: 20px;
}
</style> 